﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace DataExtractionLanguage
{
    [Serializable]
    public class Column
    {
        #region Public Properties

        /// <summary>
        /// Gets or sets the from alias from where the column will get its results
        /// </summary>
        public string SourceAlias { get; set; }

        /// <summary>
        /// Sets the path prefix for the current column.
        /// </summary>
        public string PathPrefix { private get; set; }

        /// <summary>
        /// Gets Path of the column, which was extracted from the source code.
        /// </summary>
        public string ColumnPath { get; set; }

        /// <summary>
        /// Gets XPath of the column it will be used with the extraction Library.
        /// </summary>
        public string ColumnXPath
        {
            get { return ColumnPath.Replace('.', '/'); }
        }

        /// <summary>
        /// Gets or sets the extension columns which depend on there parent column to get full path.
        /// </summary>
        public List<Column> ExtensionColumns { get; set; }

        /// <summary>
        /// Gets or sets a Token which represent the operation which will be executed on the current column.
        /// </summary>
        public PropertyMember Property { get; set; }

        /// <summary>
        /// Gets or sets the column name which is coming after the As keyword.
        /// </summary>
        public string Alias { get; set; }


        #endregion

        public Column()
        {
            ExtensionColumns = new List<Column>();
            PathPrefix = string.Empty;
            ColumnPath = string.Empty;
        }

        public void AppendColumnPath(object value)
        {
            int result = 0;
            string strValue = value.ToString();

            if (strValue == "[" || strValue == "]" || int.TryParse(strValue, out result) || ColumnPath.Length == 0)
                ColumnPath += strValue;
            else
                ColumnPath += string.Format(".{0}", strValue);
        }

        public override string ToString()
        {
            if (Property != null & !string.IsNullOrEmpty(Alias))
                return string.Format("{0} As {1}", Property, Alias);

            return string.Empty;
        }

        public Column Clone()
        {
            MemoryStream stream = new MemoryStream();
            BinaryFormatter s = new BinaryFormatter();
            s.Serialize(stream, this);
            stream.Seek(0, SeekOrigin.Begin);
            return (Column)s.Deserialize(stream);
        }
    }
}